package com.yh.csx.bsf.ods;

import com.yh.csx.bsf.core.base.BsfException;
import lombok.var;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

public class ProcessUtils {
    public static boolean isWinOs(){
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")){
            return true;
        }
        return false;
    }
    public static List<String> cmd(String cmd,boolean iswaitForResult){
        List<String> strList = new ArrayList<String>();
        try {
            var cmds = !isWinOs()?new String[]{"/bin/sh","-c",cmd}:new String[]{"cmd","/c",cmd};
            Process process = Runtime.getRuntime().exec(cmds);
           try( InputStreamReader ir = new InputStreamReader(process.getInputStream())) {
               LineNumberReader input = new LineNumberReader(ir);
               String line;
               if(iswaitForResult) {
                   process.waitFor();
                   while ((line = input.readLine()) != null) {
                       strList.add(line);
                   }
               }
               else
               {
                    return null;
               }

           }
        } catch (Exception e) {
            throw new BsfException(e);
        }
        return strList;
    }


    public static boolean isRunning(String processName) {
        String ls_1="";
        Process process=null;
        try{
            process = Runtime.getRuntime().exec("ps -ef|grep "+processName);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((ls_1 = bufferedReader.readLine()) != null) {
                if (ls_1.startsWith(processName)) {
                    return true;
                }
            }
            //process.waitFor();
        }catch (Exception e){
            throw new BsfException(e);
        }
        finally {
            process.destroy();
        }
        return false;
    }
}
